package com.gjr.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gjr.commonutils.Result;
import com.gjr.eduservice.entity.EduChapter;
import com.gjr.eduservice.entity.chapter.ChapterVo;
import com.gjr.eduservice.service.EduChapterService;
import com.gjr.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程章节 前端控制器
 * </p>
 *
 * @author gjr
 * @since 2022-09-01
 */
@Api(description = "课程章节管理")
@CrossOrigin        //跨域
@RestController
@RequestMapping("/eduservice/chapter")
public class EduChapterController {
    @Autowired
    private EduChapterService eduChapterService;

    /**
     * 课程大纲列表，根据课程id进行查询
     *
     * @param courseId 课程id
     * @return 返回章节和小节
     */
    @ApiOperation(value = "嵌套章节数据列表")
    @GetMapping("/getChapterVideo/{courseId}")
    public Result<?> getChapterVideo(@PathVariable String courseId) {
        List<ChapterVo> chapterVoList = eduChapterService.getChapterVideoByCourseId(courseId);

        return Result.ok().data("allChapterVideo", chapterVoList);
    }

    /**
     * 根据章节id查询
     *
     * @param chapterId 章节id
     * @return 章节对象
     */
    @GetMapping("/getChapterInfo/{chapterId}")
    public Result<?> getChapterInfo(@PathVariable String chapterId) {
        EduChapter eduChapter = eduChapterService.getOne(new LambdaQueryWrapper<EduChapter>()
                .eq(EduChapter::getId, chapterId), false);

        return Result.ok().data("eduChapter", eduChapter);
    }

    /**
     * 添加 or 修改章节
     *
     * @param eduChapter 章节对象
     * @return 结果
     */
    @PostMapping("/addOrUpdateChapter")
    public Result<?> addOrUpdateChapter(@RequestBody EduChapter eduChapter) {
        boolean empty = ObjectUtils.isEmpty(eduChapter.getId());

        if (empty) {
            boolean save = eduChapterService.save(eduChapter);
            if (!save) return Result.error();
        } else {
            boolean update = eduChapterService.updateById(eduChapter);
            if (!update) return Result.error();
        }

        return Result.ok();
    }

    /**
     * 删除章节：如果该章节下有小节不能完成删除
     *
     * @param chapterId 章节id
     * @return 返回值
     */
    @DeleteMapping("/{chapterId}")
    public Result<?> deteleChapter(@PathVariable String chapterId) {
        boolean flag = eduChapterService.deteleChapter(chapterId);

        if (flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }
}

